package cn.com.jenson.common;

import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;

import java.util.List;
import java.util.stream.Collectors;

/**
 * BasicVo <br>
 * 用于继承
 * <p>
 * 将Entity转换为Vo的方法类<br>
 * 及Vo公共方法类的集合
 * </p>
 *
 * @param <E> Entity
 * @param <V> Vo
 */
public abstract class BasicVo<E extends BasicEntity, V> {

    /**
     * 实体类转换为Vo
     *
     * @param e     Entity
     * @param clazz Vo 的class
     * @return Vo
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public V fromEntity(E e, Class<V> clazz) throws InstantiationException, IllegalAccessException {
        V v = (V) clazz.newInstance();
        BeanUtils.copyProperties(e, v);
        return v;
    }

    /**
     * 实体类集合转换为Vo集合
     *
     * @param eList Entity列表
     * @param clazz Vo 的class
     * @return Vo列表
     */
    public List<V> fromEntities(List<E> eList, Class<V> clazz) {
        return eList.stream().map(item -> {
            try {
                return fromEntity(item, clazz);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
    }

    /**
     * 实体类Page转 换为Vo的Page
     *
     * @param ePage 实体类Page
     * @param clazz Vo的class
     * @return Vo的Page
     */
    public Page<V> fromEntities(Page<E> ePage, Class<V> clazz) {
        return new PageImpl<>(fromEntities(ePage.getContent(), clazz), ePage.getPageable(), ePage.getTotalElements());
    }
}
